package com.jiefutong.zyt;

import android.content.Intent;
import android.content.res.Resources;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.jiefutong.zyt.adapter.AutoScrollImgPagerAdapter;
import com.jiefutong.zyt.apiservice.ApiService;
import com.jiefutong.zyt.bean.GoodsCollectVO;
import com.jiefutong.zyt.bean.GoodsDetailVO;
import com.jiefutong.zyt.http.XCRRestProvider;
import com.jiefutong.zyt.utils.TipsUtil;
import com.jiefutong.zyt.view.AutoScrollViewPager;
import com.squareup.picasso.Picasso;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class GoodsDetailActivity extends  BaseActivity{
    private ImageButton backBtn;
    private TextView titleText;
    private AutoScrollViewPager autoScrollViewPager;
    private AutoScrollImgPagerAdapter autoScrollImgPagerAdapter;
    private RadioGroup dotsGroup;

    private TextView nameTV;
    private TextView priceTV;
    private TextView postageTV;
    private TextView salesTV;
    private TextView areaTV;
    private TextView skuTV;
    private WebView webview;
    private TextView collectTV;
    private TextView buyTV;
    ApiService apiService= XCRRestProvider.getInstance().create(ApiService.class);
    private int itemId=0;
    List<String> bannerList=new ArrayList<>();

    int width=0;
    int height=0;
    GoodsDetailVO.DataBean.DetailBean detailBean;
    GoodsDetailVO.DataBean dataBean;

    List<GoodsDetailVO.DataBean.SpecDataBean.SpecAttrBean> skuList=new ArrayList<>();
    List<GoodsDetailVO.DataBean.SpecDataBean.SpecListBean> skuValueList=new ArrayList<>();

    GoodsDetailVO.DataBean.SpecDataBean.SpecListBean specListBean=null;
    int skuId=0;
    int buyType=0;//1购买 2收藏

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);
        itemId=getIntent().getIntExtra("itemId",0);
        Resources resources = this.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density1 = dm.density;
        width = dm.widthPixels;
        height = dm.heightPixels;

        initView();
        loadDatas();
        skuTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                input();
            }
        });

        collectTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buyType=2;
                collect();
            }
        });
        buyTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buyType=1;
                if(dataBean.getSpecData()!=null){
                    input();
                }else{
                    Intent intent=new Intent(GoodsDetailActivity.this,GoodsBuyActivity.class);
                    intent.putExtra("itemId",detailBean.getItem_id());
                    intent.putExtra("itemNum","1");
                    intent.putExtra("itemSkuId",skuId);
                    startActivity(intent);
                }

            }
        });


    }
    private void collect(){
        Map<String,Object> map=new HashMap<>();
        map.put("item_id",detailBean.getItem_id());
        Call<GoodsCollectVO> call=apiService.goodsCollect(map);
        call.enqueue(new Callback<GoodsCollectVO>() {
            @Override
            public void onResponse(Call<GoodsCollectVO> call, Response<GoodsCollectVO> response) {
                if(response.isSuccessful()){
                    GoodsCollectVO collectVO=response.body();
                    Toast.makeText(getBaseContext(),collectVO.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<GoodsCollectVO> call, Throwable t) {
                Toast.makeText(getBaseContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });

    }

    /**
     * 富文本适配
     */
    private String getHtmlData(String bodyHTML) {
        String head = "<head>"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
                + "<style>img{width: 100%; height:auto;}</style>"
                + "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }

    private void loadDatas() {
        Map<String,Object> map=new HashMap<>();
        map.put("item_id",itemId);
        Call<GoodsDetailVO> call=apiService.getGoodsDetail(map);
        call.enqueue(new Callback<GoodsDetailVO>() {
            @Override
            public void onResponse(Call<GoodsDetailVO> call, Response<GoodsDetailVO> response) {
                if(response.isSuccessful()){
                    GoodsDetailVO detailVO=response.body();
                    if(detailVO.getCode()==200){
                        dataBean=detailVO.getData();
                        detailBean=dataBean.getDetail();
                        if(dataBean.getSpecData()!=null){
                            skuList=dataBean.getSpecData().getSpec_attr();
                            skuValueList=dataBean.getSpecData().getSpec_list();

                        }else{
                            skuId=detailBean.getSku().get(0).getItem_sku_id();
                        }
                        if(detailBean.getImage()!=null&&detailBean.getImage().size()>0){
                            for(int i=0;i<detailBean.getImage().size();i++){
                                bannerList.add(detailBean.getImage().get(i).getFile_path());
                            }
                        }
                        setBannerData(bannerList);
                        nameTV.setText(detailBean.getName());
                        postageTV.setText("快递："+detailBean.getDelivery_desc());
                        salesTV.setText("销量"+detailBean.getSales_num());
                        priceTV.setText("￥"+detailBean.getSku().get(0).getItem_price()+"+"+detailBean.getSku().get(0).getCredit1()+"金币");
                        // webview.loadUrl(detailBean.getContent());
                        System.out.println("----ur:"+detailBean.getContent());
                        //  webview.loadData(detailBean.getContent(), "text/html; charset=UTF-8", null);
                        webview.loadDataWithBaseURL(null,  getHtmlData(detailBean.getContent()), "text/html", "utf-8", null);

                    }
                }
            }

            @Override
            public void onFailure(Call<GoodsDetailVO> call, Throwable t) {

            }
        });

    }

    private PopupWindow mPopupWindow;
    TextView skuPriceTV;
    TextView stockTV;
    ListView listView;
    TextView submitTV;
    TextView  numTV;
    public void input(){
        View view=View.inflate(GoodsDetailActivity.this,R.layout.bottom_goods_detail_buy,null);
        ImageView imgIV=view.findViewById(R.id.bootomGoodsDetail_imgIV);
        skuPriceTV=view.findViewById(R.id.bootomGoodsDetail_priceTV);
        stockTV=view.findViewById(R.id.bootomGoodsDetail_stockTV);
        listView=view.findViewById(R.id.bootomGoodsDetail_listview);
        submitTV=view.findViewById(R.id.bootomGoodsDetail_submitTV);
        numTV=view.findViewById(R.id.bootomGoodsDetail_numTV);

        mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        TipsUtil.setBackgroundAlpha(this, 0.4f);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.showAtLocation(buyTV, Gravity.BOTTOM,0,0);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                TipsUtil.setBackgroundAlpha(GoodsDetailActivity.this, 1.0f);
            }
        });


        if (!TextUtils.isEmpty(dataBean.getDetail().getThumb())) {
            Picasso.with(GoodsDetailActivity.this).load(dataBean.getDetail().getThumb()).resize(178, 178).into(imgIV);
        }
        SkuAdapter adapter=new SkuAdapter();
        listView.setAdapter(adapter);

        submitTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //
                //购买
                Intent intent=new Intent(GoodsDetailActivity.this,GoodsBuyActivity.class);
                intent.putExtra("itemId",detailBean.getItem_id());
                intent.putExtra("itemNum",numTV.getText());
                intent.putExtra("itemSkuId",skuId);
                startActivity(intent);
            }
        });

      /*  if (!TextUtils.isEmpty(detailBean.getContent())) {
            Picasso.with(getContext()).load(data.getThumb()).into(imgIV);
        }else {
            imgIV.setImageResource(R.drawable.jft_img_zhaishipixmap);
        }*/

        //MyExtendableListViewAdapter adapter=new MyExtendableListViewAdapter();
        // listView.setAdapter(adapter);
        //setListViewHeightBasedOnChildren(listView);


    }

    private void initView() {
        titleText = (TextView) findViewById(R.id.titleText);
        titleText.setText("商品详情");
        backBtn = (ImageButton) findViewById(R.id.backBtn);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        autoScrollViewPager =  findViewById(R.id.goodsDetail_autoScrollViewPager);
        dotsGroup=findViewById(R.id.goodsDetail_dotsGroup);
        nameTV = findViewById(R.id.goodsDetail_nameTV);
        priceTV = findViewById(R.id.goodsDetail_priceTV);
        postageTV = findViewById(R.id.goodsDetail_postageTV);
        salesTV = findViewById(R.id.goodsDetail_salesTV);
        areaTV = findViewById(R.id.goodsDetail_areaTV);
        skuTV = findViewById(R.id.goodsDetail_skuTV);
        webview = findViewById(R.id.goodsDetail_webview);
        collectTV = findViewById(R.id.goodsDetail_collectTV);
        buyTV = findViewById(R.id.goodsDetail_buyTV);

        WebSettings settings = webview.getSettings();
        settings.setUseWideViewPort(true);
        settings.setSupportZoom(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
    }

    /**
     * 动态设置ListView的高度
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(GridView listView) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = 4;// listView.getNumColumns();
        int totalHeight = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; i < listAdapter.getCount(); i  +=col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }

        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
      /*  // 设置margin
        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);*/
        // 设置参数
        listView.setLayoutParams(params);
    }



    /**
     * 设置Banner中的数据
     *
     * @param list
     */
    private void setBannerData( List<String> list) {
        LayoutInflater layoutInflater = LayoutInflater.from(GoodsDetailActivity.this);
        int w;
        int dpi = getResources().getDisplayMetrics().densityDpi;
        if (dpi == DisplayMetrics.DENSITY_HIGH) {
            w = 12;
        } else if (dpi == DisplayMetrics.DENSITY_XHIGH) {
            w = 15;
        } else {
            w = 25;
        }
        dotsGroup.removeAllViews();
        for (int i = 0, size =list.size(); i < size; i++) {
            RadioButton dotRadioBtn = (RadioButton) layoutInflater.inflate(R.layout.layout_question_dot, null);
            RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(w, w);
            params.leftMargin = 7;
            params.rightMargin = 7;
            dotRadioBtn.setId(i);
            dotRadioBtn.setLayoutParams(params);
            dotsGroup.addView(dotRadioBtn);
        }
        dotsGroup.check(0);
        autoScrollViewPager.setOffscreenPageLimit(list.size());
        autoScrollImgPagerAdapter = new AutoScrollImgPagerAdapter(GoodsDetailActivity.this, list);
        if (list.size() > 1) {
            autoScrollImgPagerAdapter.setInfiniteLoop(true);
            autoScrollViewPager.setInterval(4000); // 4秒钟轮训一次
            autoScrollViewPager.startAutoScroll();
        } else {
            autoScrollImgPagerAdapter.setInfiniteLoop(false);
        }
        autoScrollViewPager.setAdapter(autoScrollImgPagerAdapter);
        autoScrollViewPager.setOnPageChangeListener(new AutoScrollImgListener());
    }

    /**
     * 图片轮播监听器
     */
    private class AutoScrollImgListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            int pos = autoScrollImgPagerAdapter.getPosition(position);
            dotsGroup.check(pos);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }



    public class SkuAdapter extends BaseAdapter {
        String[] selStr=new String[skuList.size()];
        @Override
        public int getCount() {
            return skuList.size();
        }

        @Override
        public Object getItem(int position) {
            return skuList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public class ViewHolder{
            private TextView titleTV;
            private GridView gridView;
            private TagFlowLayout contentLL;

        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder=null;
            if(convertView==null){
                convertView=View.inflate(GoodsDetailActivity.this,R.layout.item_parents,null);
                viewHolder=new ViewHolder();
                convertView.setTag(viewHolder);
            }else{
                viewHolder= (ViewHolder) convertView.getTag();
            }
            final GoodsDetailVO.DataBean.SpecDataBean.SpecAttrBean data=skuList.get(position);
            viewHolder.titleTV=convertView.findViewById(R.id.itemParents_titleTV);
            viewHolder.contentLL=convertView.findViewById(R.id.itemParents_contentLL);
            viewHolder.titleTV.setText(data.getGroup_name());

            final List<String> strList=new ArrayList<>();
            for(int i=0;i<data.getSpec_items().size();i++){
                strList.add(data.getSpec_items().get(i).getSpec_value());
            }

            viewHolder.contentLL.setAdapter(new TagAdapter<String>(strList)
            {
                @Override
                public View getView(FlowLayout parent, int position, String s)
                {
                    TextView tv = (TextView) View.inflate(getBaseContext(),R.layout.item_child,null);
                    tv.setText(s);
                    return tv;
                }

                @Override
                public void onSelected(int position, View view) {
                    super.onSelected(position, view);
                    TextView textView= (TextView) view;
                    textView.setBackgroundResource(R.drawable.corner_orange);
                    textView.setTextColor(0xffffffff);
                }

                @Override
                public void unSelected(int position, View view) {
                    super.unSelected(position, view);
                    TextView textView= (TextView) view;
                    textView.setBackgroundResource(R.drawable.corner_e9);
                    textView.setTextColor(0xff333333);
                }
            });

            viewHolder.contentLL.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
                @Override
                public void onSelected(Set<Integer> selectPosSet) {
                    int id=data.getSpec_items().get((Integer) selectPosSet.toArray()[0]).getItem_id();
                    selStr[position]=String.valueOf(id);
                    if(position==skuList.size()-1){
                        String[] getSku=new String[skuList.size()];
                        //申请接口
                        for(int i=0;i<skuValueList.size();i++){
                            GoodsDetailVO.DataBean.SpecDataBean.SpecListBean listBean=skuValueList.get(i);
                            getSku=listBean.getSpec_sku_id().split("_");
                            if(Arrays.equals(getSku,selStr)){
                                skuId=listBean.getItem_sku_id();
                                //判断选择的和是否相等
                                skuPriceTV.setText(listBean.getForm().getItem_price()+"元+"+listBean.getForm().getCredit1()+"金币");
                                stockTV.setText(""+listBean.getForm().getStock_num());
                            }

                        }
                    }
                }
            });

            return convertView;
        }




    }



}
